package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author feng js
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        if (adUserDto == null || StringUtils.isBlank(adUserDto.getName()) || StringUtils.isBlank(adUserDto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "账号或密码不能为空");
        }
        QueryWrapper<AdUser> wrapper = new QueryWrapper<>();
        wrapper.eq("name",adUserDto.getName());
        AdUser adUser = getOne(wrapper);
        if (adUser == null) {

            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户不存在");
        }
        String salt = adUser.getSalt();
        String pasw = adUserDto.getPassword();
        String md5Pasword = DigestUtils.md5DigestAsHex((pasw + salt).getBytes());
        if (!md5Pasword.equals(adUser.getPassword())) {

            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("token",AppJwtUtil.getToken(adUser.getId().longValue()));
        adUser.setPassword("");
        adUser.setSalt("");
        map.put("user",adUser);
        return ResponseResult.okResult(map);
    }
}
